/**
 * 格式化日期
 * @param {Date|String|Number} date 日期对象/日期字符串/时间戳
 * @param {String} format 格式化模板，如 'YYYY-MM-DD HH:mm:ss'
 * @returns {String} 格式化后的日期字符串
 */
export function formatDate(date, format = "YYYY-MM-DD") {
  if (!date) return "";

  if (typeof date === "string" || typeof date === "number") {
    date = new Date(date);
  }

  if (!(date instanceof Date) || isNaN(date.getTime())) {
    return "";
  }

  const year = date.getFullYear();
  const month = date.getMonth() + 1;
  const day = date.getDate();
  const hour = date.getHours();
  const minute = date.getMinutes();
  const second = date.getSeconds();

  return format
    .replace(/YYYY/g, year)
    .replace(/YY/g, String(year).slice(2))
    .replace(/MM/g, padZero(month))
    .replace(/M/g, month)
    .replace(/DD/g, padZero(day))
    .replace(/D/g, day)
    .replace(/HH/g, padZero(hour))
    .replace(/H/g, hour)
    .replace(/hh/g, padZero(hour % 12 || 12))
    .replace(/h/g, hour % 12 || 12)
    .replace(/mm/g, padZero(minute))
    .replace(/m/g, minute)
    .replace(/ss/g, padZero(second))
    .replace(/s/g, second);
}

/**
 * 数字前补零
 * @param {Number} num 数字
 * @returns {String} 补零后的字符串
 */
function padZero(num) {
  return String(num).padStart(2, "0");
}

/**
 * 获取相对时间描述（刚刚、几分钟前、几小时前、几天前等）
 * @param {Date|String|Number} date 日期对象/日期字符串/时间戳
 * @returns {String} 相对时间描述
 */
export function getRelativeTime(date) {
  if (!date) return "";

  if (typeof date === "string" || typeof date === "number") {
    date = new Date(date);
  }

  if (!(date instanceof Date) || isNaN(date.getTime())) {
    return "";
  }

  const now = new Date();
  const diff = now.getTime() - date.getTime();

  // 转换为秒
  const seconds = Math.floor(diff / 1000);

  if (seconds < 60) {
    return "刚刚";
  }

  // 转换为分钟
  const minutes = Math.floor(seconds / 60);

  if (minutes < 60) {
    return `${minutes}分钟前`;
  }

  // 转换为小时
  const hours = Math.floor(minutes / 60);

  if (hours < 24) {
    return `${hours}小时前`;
  }

  // 转换为天
  const days = Math.floor(hours / 24);

  if (days < 30) {
    return `${days}天前`;
  }

  // 超过30天显示具体日期
  return formatDate(date, "YYYY-MM-DD");
}

/**
 * 获取日期范围
 * @param {String} type 范围类型：today, yesterday, week, month, year
 * @returns {Array} 开始日期和结束日期的数组 [startDate, endDate]
 */
export function getDateRange(type) {
  const now = new Date();
  let startDate, endDate;

  switch (type) {
    case "today":
      startDate = new Date(now.getFullYear(), now.getMonth(), now.getDate());
      endDate = new Date(
        now.getFullYear(),
        now.getMonth(),
        now.getDate(),
        23,
        59,
        59
      );
      break;
    case "yesterday":
      startDate = new Date(
        now.getFullYear(),
        now.getMonth(),
        now.getDate() - 1
      );
      endDate = new Date(
        now.getFullYear(),
        now.getMonth(),
        now.getDate() - 1,
        23,
        59,
        59
      );
      break;
    case "week":
      const day = now.getDay() || 7; // 将周日的0转换为7
      startDate = new Date(
        now.getFullYear(),
        now.getMonth(),
        now.getDate() - day + 1
      );
      endDate = new Date(
        now.getFullYear(),
        now.getMonth(),
        now.getDate() + (7 - day),
        23,
        59,
        59
      );
      break;
    case "month":
      startDate = new Date(now.getFullYear(), now.getMonth(), 1);
      endDate = new Date(now.getFullYear(), now.getMonth() + 1, 0, 23, 59, 59);
      break;
    case "year":
      startDate = new Date(now.getFullYear(), 0, 1);
      endDate = new Date(now.getFullYear(), 11, 31, 23, 59, 59);
      break;
    default:
      startDate = new Date(now.getFullYear(), now.getMonth(), now.getDate());
      endDate = new Date(
        now.getFullYear(),
        now.getMonth(),
        now.getDate(),
        23,
        59,
        59
      );
  }

  return [startDate, endDate];
}

/**
 * 计算两个日期之间的天数
 * @param {Date|String|Number} startDate 开始日期
 * @param {Date|String|Number} endDate 结束日期
 * @returns {Number} 天数
 */
export function getDaysBetween(startDate, endDate) {
  if (!startDate || !endDate) return 0;

  if (typeof startDate === "string" || typeof startDate === "number") {
    startDate = new Date(startDate);
  }

  if (typeof endDate === "string" || typeof endDate === "number") {
    endDate = new Date(endDate);
  }

  if (
    !(startDate instanceof Date) ||
    isNaN(startDate.getTime()) ||
    !(endDate instanceof Date) ||
    isNaN(endDate.getTime())
  ) {
    return 0;
  }

  // 转换为不带时分秒的日期
  const start = new Date(
    startDate.getFullYear(),
    startDate.getMonth(),
    startDate.getDate()
  );
  const end = new Date(
    endDate.getFullYear(),
    endDate.getMonth(),
    endDate.getDate()
  );

  // 计算天数
  const diff = Math.abs(end - start);
  return Math.round(diff / (24 * 60 * 60 * 1000));
}
